package top.zywork.service.impl;

import com.fasterxml.jackson.databind.util.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.zywork.common.BeanUtils;
import top.zywork.constant.ShippingAddressConstant;
import top.zywork.dao.ShippingAddressDAO;
import top.zywork.dos.ShippingAddressDO;
import top.zywork.dto.ShippingAddressDTO;
import top.zywork.mapper.ShippingAddressMapper;
import top.zywork.query.ShippingAddressQuery;
import top.zywork.service.AbstractBaseService;
import top.zywork.service.ShippingAddressService;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

/**
 * ShippingAddressServiceImpl服务接口实现类<br/>
 *
 * 创建于2019-06-27<br/>
 *
 * @author http://zywork.top 王振宇
 * @version 1.0
 */
@Service(value = "shippingAddressService")
public class ShippingAddressServiceImpl extends AbstractBaseService implements ShippingAddressService {

    private ShippingAddressDAO shippingAddressDAO;

    @Resource
    private ShippingAddressMapper shippingAddressMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateAddress(ShippingAddressDTO shippingAddressDTO) {
        Integer version = shippingAddressDAO.getVersionById(shippingAddressDTO.getId());
        version = version == null ? 1 : version;
        shippingAddressDTO.setVersion(version + 1);
        if (shippingAddressDTO.getIsDefault() == ShippingAddressConstant.IS_DEFAULT_TRUE) {
            shippingAddressDAO.updateNoDefault(shippingAddressDTO.getUserId());
        }
        int updateRows = shippingAddressMapper.updateById(BeanUtils.copy(shippingAddressDTO,ShippingAddressDO.class));
        return updateRows;
    }

    @Override
    public int updateNoDefault(Long userId) {
        return shippingAddressDAO.updateNoDefault(userId);
    }

    @Override
    public int saveAddress(ShippingAddressDTO shippingAddressDTO) {
        if (ShippingAddressConstant.IS_DEFAULT_TRUE == shippingAddressDTO.getIsDefault()) {
            // 当前需要保存的地址设置了默认地址，需要把其他的默认地址设置回非默认
            shippingAddressDAO.updateNoDefault(shippingAddressDTO.getUserId());
        }
        ShippingAddressDO copy = BeanUtils.copy(shippingAddressDTO, ShippingAddressDO.class);
        int saveRows = shippingAddressDAO.save(copy);
        return saveRows;
    }

    @Autowired
    public void setShippingAddressDAO(ShippingAddressDAO shippingAddressDAO) {
        super.setBaseDAO(shippingAddressDAO);
        this.shippingAddressDAO = shippingAddressDAO;
    }

    @PostConstruct
    public void init() {
        super.init(ShippingAddressDO.class, ShippingAddressDTO.class);
    }
}
